local rule = fk.CreateSkill {
  name = "#m_1v3_rule&",
}

-- 起始手牌，神吕布8张，二号位3，三号位4， 四号位5
rule:addEffect(fk.DrawInitialCards, {
  priority = 0.001,
  can_refresh = function(self, event, target, player, data)
    return target == player
  end,
  on_refresh = function(self, event, target, player, data)
    if player.seat == 1 then
      data.num = 8
    else
      data.num = player.seat + 1
    end
  end,
})

-- 休整归来摸牌
rule:addEffect(fk.AfterPlayerRevived, {
  priority = 0.001,
  can_refresh = function(self, event, target, player, data)
    return player.tag["hulaoRest"] --and player.hp < 6
    and target == player
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    --player:drawCards(6 - player.hp, rule.name)
    local general = Fk.generals[player.general]
    player.hp = general.hp
    player.maxHp = general.maxHp
    player.shield = general.shield
    player.kingdom = general.kingdom
    local deputyGeneral = Fk.generals[player.deputyGeneral]
    if room:getSettings('enableDeputy') and deputyGeneral then
      player.maxHp = player:getGeneralMaxHp()
      player.hp = math.floor((deputyGeneral.hp + general.hp) / 2)
      player.shield = math.min(general.shield + (deputyGeneral and deputyGeneral.shield or 0), 5)
    end
    for _, v in ipairs({"shield", "maxHp", "hp", "kingdom"}) do
      room:broadcastProperty(player, v)
    end
    player:drawCards(3, rule.name)
  end,
})

-- 盟军死亡进入休整
rule:addEffect(fk.BeforeGameOverJudge, {
  priority = 0.001,
  can_refresh = function(self, event, target, player, data)
    return target == player and player.role ~= "lord"
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local n = room:getSettings('enableDeputy') and 2 or 1
    player._splayer:setDied(false)
    if n == 1 then
      room:setPlayerRest(player, 3)
    else
      room:setPlayerRest(player, 6)
    end
    player.tag["hulaoRest"] = true
    local onlyLvbu = #room:getOtherPlayers(room:getLord()) == 0
    if onlyLvbu then
      room:gameOver("lord")
    end
    for _, p in ipairs(room:getOtherPlayers(player)) do
      if p.role == player.role and not p.dead and p.rest == 0 then
        if n == 2 then
          if room:askToSkillInvoke(p, {
              skill_name = "PickLegacy",
              prompt = "#m_1v3_death_draw",
            }) then
            p:drawCards(1, "game_rule")
          end
        else
          local choices = { "draw2", "Cancel" }
          if p:isWounded() then
            table.insert(choices, 2, "recover")
          end
          local choice = room:askToChoice(p, {
            choices = choices,
            skill_name = "PickLegacy",
          })
          if choice == "draw2" then
            p:drawCards(2, "game_rule")
          else
            room:recover {
              who = p,
              num = 1,
              skillName = "game_rule",
            }
          end
        end
      end
    end
  end,
})
rule:addEffect(fk.BeforeTurnStart, {
  priority = 0.001,
  can_refresh = function(self, event, target, player, data)
    return target == player and player.tag["hulaoRest"]
  end,
  on_refresh = function(self, event, target, player, data)
    player.tag["hulaoRest"] = false
  end,
})

--暴怒！
local spec = {
  ---@param player ServerPlayer
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local round = room.logic:getCurrentEvent():findParent(GameEvent.Round)
    room:notifySkillInvoked(player, "m_1v3_convert", "big")
    room:setTag("m_1v3_phase2", true)
    local generals = {}
    for _, g in pairs(Fk.generals) do
      if g.hulao_status == 2 and
          g.trueName == Fk.generals[player.general].trueName and
          not table.contains(room.disabled_packs, g.package.name) and
          not table.contains(room.disabled_generals, g) then
        table.insert(generals, g)
      end
    end
    generals = table.map(generals, Util.NameMapper)
    local general = room:askToChooseGeneral(player, {
      generals = generals,
      n = 1,
    })
    room:changeMaxHp(player, Fk.generals[general].maxHp - player.maxHp)
    room:changeHp(player, Fk.generals[general].hp - player.hp, nil, rule.name)
    room:changeHero(player, general, false, false, true, false, false)
    if type(general) == "string" and Fk.generals[general] then
      local deputy = Fk.generals[general].hulao_deputy
      if deputy then
        room:changeHero(player, deputy, false, true, true, true, false)
      end
    end

    player:throwAllCards("j")
    player:reset()
    --[[
    if player.chained then
      player:setChainState(false)
    end
    if not player.faceup then
      player:turnOver()
    end
    --]]
    if round then
      room.current = player
      round:shutdown()
    end
  end,
}
rule:addEffect(fk.BeforeHpChanged, {
  priority = 0.001,
  can_refresh = function(self, event, target, player, data)
    local num = Fk.generals[player.general].hulao_status_2_hp or 4  -- 2阶起始血量，等有多个2阶再改
    return target == player and player.role == "lord" and not player.room:getTag("m_1v3_phase2") and
    (player.hp + data.num) <= num
  end,
  on_refresh = spec.on_refresh,
})
rule:addEffect(fk.AfterDrawPileShuffle, {
  priority = 0.001,
  can_refresh = function(self, event, target, player, data)
    return player.role == "lord" and not player.room:getTag("m_1v3_phase2")
  end,
  on_refresh = spec.on_refresh,
})

return rule
